package org.jeecg.modules.bj.controller;

import org.jeecg.modules.bj.service.BjCreateFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bj/createfile")
public class BjCreateFileController {

    @Autowired
    private BjCreateFileService bjCreateFileService;

    @PostMapping(value = "/createAndGetFile")
    public List<Map<String,String>> createAndGetFile(HttpServletRequest request) throws Exception{
        String proc_inst_id=request.getParameter("proc_inst_id");
        String ygid=request.getParameter("ygid");
        String num=request.getParameter("num");
        return bjCreateFileService.createAndGetFile(proc_inst_id,ygid,num);
    }

    @GetMapping(value = "/download")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException{
       String filePath=request.getParameter("filePath");
       File file=new File(filePath);
        // 配置文件下载
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            System.out.println("Download the song successfully!");
        }
        catch (Exception e) {
            System.out.println("Download the song failed!");
        }
        finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
